package com.eascs.afterloan.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.eascs.admin.o2o.internal.util.BaseUserUtil;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.recordlog.constant.O2oLogType;
import com.eascs.admin.recordlog.servcie.O2oRecordLogService;
import com.eascs.afterloan.entity.AdvancedPayment;
import com.eascs.afterloan.form.AdvanceSettleForm;
import com.eascs.afterloan.service.AdvanceSettleService;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;
import com.eascs.loan.vo.O2oRepaymentRecordVo;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.web.sso.UserHolder;
import com.eascs.web.url.UrlHelper;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.type.SystemModule;
import com.eascs.workflow.common.vo.ModelResult;

@RestController
@RequestMapping("/advanceSettleRest")
public class AdvanceSettleRestController {
	private static Logger logger = LoggerFactory.getLogger(AdvanceSettleRestController.class);
	@Autowired
	AdvanceSettleService advanceSettleService;
	@Autowired
	O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	private O2oRecordLogService o2oRecordLogService;
	@Autowired
	BaseUserUtil userUtils;
	@Autowired
	private O2oLoanUserService o2oLoanUserService;

	@Autowired
	private BaseUtils baseUtils;

	//贷款详情--发起贷款结清--保存并启动流程
	@RequestMapping(value = "/saveAdvanceSettle")
	public BaseRestResult<String> approval_AdvanceSettle(AdvanceSettleForm advanceSettleForm) {
		// 判断
		if (StringUtil.isEmpty(advanceSettleForm.getLoanapplyNo())) {
			return BaseRestResult.warn("贷款单号不能为空");
		}
		if (StringUtil.isEmpty(advanceSettleForm.getPayName())) {
			return BaseRestResult.warn("付款人不能为空");
		}
		if (StringUtil.isEmpty(advanceSettleForm.getPayDate())) {
			return BaseRestResult.warn("付款日期不能为空");
		}
		

		AdvancedPayment run_advancedPayment = advanceSettleService.queryEntity(advanceSettleForm.getLoanapplyNo(),
				StatusContexts.WFTYPE_STATUS_RUN);;  
		
		if(run_advancedPayment!=null){
			return BaseRestResult.warn("您已经发起过了提前还款结清流程，请勿重复发起");
		}

		AdvancedPayment advancedPayment = advanceSettleService.queryEntity(advanceSettleForm.getLoanapplyNo(),
				StatusContexts.WFTYPE_STATUS_NEW);
		
	
		if (advancedPayment == null) {
			AdvancedPayment advance = new AdvancedPayment();
			O2oLoanapplyEntity loanapply = o2oLoanapplyService.findById(advanceSettleForm.getLoanapplyNo());
			advance.setLoanapplyNo(advanceSettleForm.getLoanapplyNo());
			advance.setBillCode(loanapply.getBillCode());
			advance.setBillStatus(StatusContexts.WFTYPE_STATUS_NEW);
			advance.setCreatorId(userUtils.getCreateOr());
			advance.setCreatTime(userUtils.getCreateTime());
			advance.setCreatorName(userUtils.getUserName());
			advance.setUpdator(userUtils.getUserName());
			advance.setUpdateTime(userUtils.getUpdateTime());
			advance.setLoanerName(advanceSettleForm.getLoanerName());
			advance.setPayName(advanceSettleForm.getPayName());
			advance.setPayDate(DateUtils.formateStandDate(advanceSettleForm.getPayDate()));
			advance.setBillStatus(StatusContexts.WFTYPE_STATUS_NEW);
			advanceSettleService.save(advance);
			
		} else {
			
			advancedPayment.setPayName(advanceSettleForm.getPayName());
			advancedPayment.setPayDate(DateUtils.formateStandDate(advanceSettleForm.getPayDate()));
			advanceSettleService.updateById(advancedPayment);
		}
		AdvancedPayment ad = advanceSettleService.queryEntity(advanceSettleForm.getLoanapplyNo(),
				StatusContexts.WFTYPE_STATUS_NEW);
		if (AdvanceSettleForm.TYPE_SAVEANDSTART.equals(advanceSettleForm.getType())) { // 如果是保存并启动，调用启动方法
			
			advancedPaymentStartUp(ad.getId());
		}
		return BaseRestResult.info("操作成功").andRedirect(UrlHelper.build("/advanceSettle/list"));
	}
	
	//贷款详情--发起贷款结清--保存并启动流程--存日志
	@RequestMapping(value = "/advancedPaymentStartUp")
	public BaseRestResult<String> advancedPaymentStartUp(String referId) {
		AdvancedPayment advancedPayment = advanceSettleService.queryById(referId); 
	 
		O2oLoanapplyEntity	apply = o2oLoanapplyService.fingByBillCode(advancedPayment.getBillCode());
		
		// 存库成功 启动退费流程
		ModelResult<Boolean> modelResult = advanceSettleService.advancedPayment(apply);
		// 流程启动后更新主表
		logger.info("start-up Technological process result params isSuccess:{},ErrCode:{},ErrMsg:{},etailStack:{}", modelResult.isSuccess(), modelResult.getErrCode(), modelResult.getErrMsg(), modelResult.getDetailStack());
		if (modelResult.isSuccess()) {
			// 流程启动后更新主表
			advanceSettleService.updateWorkFlowStatus(StatusContexts.WFTYPE_STATUS_RUN, apply.getLoanapplyNo());
			
			try {
				// 记录到操作日志表
				o2oLoanapplyService.saveLog(UserHolder.getUser().getCname(), O2oLogType.LOAN_STATUS_HN, "贷款详情--发起贷款结清--保存并启动流程", "借款单号为："+advancedPayment.getBillCode()+",结清日期是："+advancedPayment.getPayDate()+",付款人是："+advancedPayment.getPayName());
				// 记录到【结清操作记录】和【作废操作记录】 日志表
				o2oRecordLogService.saveLog(advancedPayment.getBillCode(), UserHolder.getUser().getCname(), O2oLogType.LOAN_STATUS_HN, advancedPayment.getPayDate(), null,"录入");
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return BaseRestResult.info("操作成功").andRedirect(UrlHelper.build("/advanceSettle/list"));
		}
		return BaseRestResult.warn(modelResult.getErrMsg());
	}
	
	
	/* * 流程中审核的详情页面
	 * @param entity
	 * @return
	 */
	@RequestMapping("/advancedPaymentView")
	public BaseRestResult<String> advancedPaymentView(O2oRepaymentRecordVo entityVo) {

		String url = "";
		String type = entityVo.getType();
		AdvancedPayment advancedPayment = null;
		String billCode = "";
		if (type == null && entityVo.getReferId() != null) { // 如果type没有值说明是查看
			advancedPayment = advanceSettleService.queryById(entityVo.getReferId());
			billCode = advancedPayment.getBillCode();
		} else {
			billCode = entityVo.getBillCode();
			
		}
		
		O2oLoanapplyEntity loanapply = o2oLoanapplyService.fingByBillCode(billCode);
		if(type!=null){
			advancedPayment=advanceSettleService.queryEntity(loanapply.getLoanapplyNo(),null);
		}	

		ViewContext.put("type", type);
		if(type!=null && type.equals("1")){
			
			String approvalUrl = baseUtils.getApprovalUrl(entityVo.getNodeAuditorId(), ProcessTemplate.SYSTEM_MODULE_O2O);// 审批代办列表详情URL
			ViewContext.put("approvalUrl", approvalUrl);
		}else
		{
			String agreeUrl = baseUtils.getApprovalAgreeUrl(advancedPayment.getLoanapplyNo(), null, SystemModule.SYSTEM_MODULE_O2O);
			ViewContext.put("agreeUrl", agreeUrl);
		}
		logger.info("工作流访问回款详情：参数billCode：【{}】", billCode);

		O2oLoanUserEntity loanUser = o2oLoanapplyService.findLoanUserEntity(loanapply.getLoanapplyNo(), loanapply.getLoanId());
		O2oLoanUserEntity materEntity = o2oLoanUserService.findSpouseId(loanapply.getLoanId(), loanapply.getLoanapplyNo());
		ViewContext.put("advancedPayment", advancedPayment);
		ViewContext.put("loanUser", loanUser);
		ViewContext.put("loanapply", loanapply);
		ViewContext.put("materEntity", materEntity);

		if ("FINISH".equals(entityVo.getApprovalStatus()) || "PROCESSING".equals(entityVo.getApprovalStatus())) {
			String agreeUrl = baseUtils.getApprovalAgreeUrl(advancedPayment.getLoanapplyNo(), null, SystemModule.SYSTEM_MODULE_O2O);
			ViewContext.put("agreeUrl", agreeUrl);
			url = "advance/advance_payment_detail";
		} else {
			url = "advance/advance_payment_approval";
		}
		return HtmlRestResult.popHtmlFragment(url);

	}
	
	
	/**
	 * @Title: advanced_payment_model
	 * @Description: 提前还款结清模块信息
	 * @author 张庆奇
	 * @param loanapplyNo
	 * @return
	 * @return BaseRestResult<String>
	 * @throws
	 * @date 2017年4月1日 上午9:22:47
	 */
	@RequestMapping("/advanced_payment_model")
	public BaseRestResult<String>  advanced_payment_model(String loanapplyNo) {
		AdvancedPayment advancedPayment = advanceSettleService.queryEntity(loanapplyNo,null);
		ViewContext.put("advancedPayment", advancedPayment);
		return new HtmlRestResult("advance/advanced_payment_model");
	}
	
	
	/**
	 * @Title: advanced_payment_edit
	 * @Description: 提前还款编辑页面
	 * @author 张庆奇
	 * @param id
	 * @return
	 * @return BaseRestResult<String>
	 * @throws
	 * @date 2017年6月13日 下午1:51:07
	 */
	@RequestMapping("/advanced_payment_edit")
	public BaseRestResult<String>  advanced_payment_edit(String loanapplyNo) {
		AdvancedPayment advancedPayment = advanceSettleService.queryEntity(loanapplyNo,null);
		ViewContext.put("advancedPayment", advancedPayment);
		ViewContext.put("loanapplyNo", loanapplyNo);
		return HtmlRestResult.popHtmlFragment("advance/advance_payment_edit");
		
	}
	

	//贷款详情--发起贷款结清--保存并启动流程
	@RequestMapping(value = "/editAdvanceSettle")
	public BaseRestResult<String> editAdvanceSettle(AdvanceSettleForm advanceSettleForm) {
		// 判断
		if (StringUtil.isEmpty(advanceSettleForm.getLoanapplyNo())) {
			return BaseRestResult.warn("贷款单号不能为空");
		}
		if (StringUtil.isEmpty(advanceSettleForm.getPayName())) {
			return BaseRestResult.warn("付款人不能为空");
		}
		if (StringUtil.isEmpty(advanceSettleForm.getPayDate())) {
			return BaseRestResult.warn("付款日期不能为空");
		}
		

		

		AdvancedPayment advancedPayment = advanceSettleService.queryEntity(advanceSettleForm.getLoanapplyNo(),
				StatusContexts.WFTYPE_STATUS_NEW);
		
	
		if (advancedPayment == null) {
			AdvancedPayment advance = new AdvancedPayment();
			O2oLoanapplyEntity loanapply = o2oLoanapplyService.findById(advanceSettleForm.getLoanapplyNo());
			advance.setLoanapplyNo(advanceSettleForm.getLoanapplyNo());
			advance.setBillCode(loanapply.getBillCode());
			advance.setBillStatus(StatusContexts.WFTYPE_STATUS_NEW);
			advance.setCreatorId(userUtils.getCreateOr());
			advance.setCreatTime(userUtils.getCreateTime());
			advance.setCreatorName(userUtils.getUserName());
			advance.setUpdator(userUtils.getUserName());
			advance.setUpdateTime(userUtils.getUpdateTime());
			advance.setLoanerName(advanceSettleForm.getLoanerName());
			advance.setPayName(advanceSettleForm.getPayName());
			advance.setPayDate(DateUtils.formateStandDate(advanceSettleForm.getPayDate()));
			advance.setBillStatus(StatusContexts.WFTYPE_STATUS_NEW);
			advanceSettleService.save(advance);
			
		} else {
			
			advancedPayment.setPayName(advanceSettleForm.getPayName());
			advancedPayment.setPayDate(DateUtils.formateStandDate(advanceSettleForm.getPayDate()));
			advanceSettleService.updateById(advancedPayment);
		}
		
		
		return BaseRestResult.buildClosestReloadResult();
	}

}
